package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    /**
     * 添加订单
     * @param orders
     */
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Override
    public void submit(Orders orders) {
        Long userId = BaseContext.getCurrentId();//用户ID
        Long addressBookId = orders.getAddressBookId();//地址ID
        BigDecimal total=new BigDecimal(0);//订单总金额

        //用户
        User user = userService.getById(userId);
        //地址
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //购物车
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        // TODO:将购物车的数据转换为订单数据
        //生产订单ID，mybatis自带的雪花算法用法
        long ordersId = IdWorker.getId();

        //1.添加订单详情表的数据（N条）
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            //    将每一个Cart转换为OrderDetail
            OrderDetail orderDetail=new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(ordersId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));

            total=total.add(orderDetail.getAmount());//累计小计，得到总金额

            orderDetail.setImage(cart.getImage());
            orderDetailList.add(orderDetail);
        }

    //    2.添加订单表的数据（1条）
        orders.setId(ordersId);
        orders.setNumber("o_"+System.currentTimeMillis());
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(total);//总金额
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //添加订单和订单详情
        this.save(orders);
        orderDetailService.saveBatch(orderDetailList);
        //添加完成后，将购物车清空
        shoppingCartService.remove(queryWrapper);
    }
}